{% extends 'base/base.html' %}
{% load static %}

{% block head_region %}
    <title>一键升级</title>
{% endblock %}

{% block left_region %}
    <li class="layui-nav-item layui-this"><a href="{% url 'containers_manager:containersManager' %}">容器</a></li>
    <li class="layui-nav-item"><a href="{% url 'images_manager:imagesManager' %}">镜像</a></li>
{% endblock %}

{% block button_region %}
    <button id="start" type="button" class="layui-btn layui-btn-sm layui-btn-normal">启动</button>
    <button id="stop" type="button" class="layui-btn layui-btn-sm layui-btn-normal">停止</button>
    <button id="update" type="button" class="layui-btn layui-btn-sm layui-btn-normal">更新</button>
    <button id="rename" type="button" class="layui-btn layui-btn-sm layui-btn-normal">重命名</button>
    <button id="change_tag" type="button" class="layui-btn layui-btn-sm layui-btn-normal">更换镜像</button>
{% endblock %}

{#{% block data_region %}#}
{#    <table class="layui-hide" id="container_table" lay-filter="container_table"></table>#}
{#{% endblock %}#}

{% block data_region %}
    <table class="layui-table" id="container_table" lay-skin="line"
           lay-data="{limit: Number.MAX_VALUE, id:'container_table'}" lay-filter="container_table">
        <colgroup>
            <col style="width: 70px">
        </colgroup>

        <thead>
        <tr>
            <th lay-data="{field:'status', width:70}">状态</th>
            <th lay-data="{field:'name'}">容器名称</th>
            <th lay-data="{field:'image_and_tag'}">使用镜像</th>
            <th lay-data="{field:'createTime'}">创建时间</th>
            <th lay-data="{field:'upTime'}">运行时间</th>
        </tr>
        </thead>
        <tbody>
        {% if container_list %}
            {% for container in container_list %}
                {% with name=container.Names.0|slice:"1:" %}
                    <tr>
                        <td id="state">{{ container.State }}</td>
                        <td class="col-auto">{{ name }}
                            {% if container.update %}
                                <span class="layui-badge layui-bg-blue">有更新</span>
                            {% endif %}
                        </td>
                        <td>{{ container.imageNameAndTag }}</td>
                        <td class="createTime">{{ container.Created }}</td>
                        <td>{{ container.Status }}</td>
                    </tr>
                {% endwith %}
            {% endfor %}
        {% else %}
            <p>列表为空</p>
        {% endif %}
        </tbody>
    </table>
{% endblock %}

{% block footer_region %}
    <span> <span id="rowCountDisplay"></span> 个容器</span>
{% endblock %}

{% block scripts %}
    <script src="{% static 'layui/layui.js' %}"></script>
    <!-- 具体的 JavaScript 代码 -->

    <script>
        layui.use('table', function () {
            var table = layui.table;
            //监听行单击事件（双击事件为：rowDouble）
            table.on('row(container_table)', function (obj) {
                //标注选中样式
                obj.tr.addClass('layui-bg-blue active').siblings().removeClass('layui-bg-blue active');
            });
        });
    </script>

    <script>
        var tdList = document.querySelectorAll('#state');                   // 获取所有id为state的td标签

        for (var i = 0; i < tdList.length; i++) {// 遍历标签列表
            if (tdList[i].innerHTML === 'running') // 判断标签的内容
                tdList[i].innerHTML = '<span class="layui-badge-dot layui-bg-green"></span>'; // 替换标签的内容
            else if (tdList[i].innerHTML === 'exited')
                tdList[i].innerHTML = '<span class="layui-badge-dot"></span>'; // 替换标签的内容
            else
                tdList[i].innerHTML = '<span class="layui-badge-dot layui-bg-gray"></span>'; // 替换标签的内容
        }
    </script>

    <script>
        var cells = document.querySelectorAll('td.createTime');     // 获取所有类名为"createTime"的单元格
        for (var i = 0; i < cells.length; i++) {                   // 遍历单元格列表
            var timestamp = cells[i].textContent;                    // 获取时间戳
            var date = new Date(timestamp * 1000);                   // 将时间戳转换为Date对象
            cells[i].textContent = date.toLocaleString();                       // 替换原始内容为日期字符串
        }
    </script>

    <script>
        var start = document.getElementById('start');
        start.onclick = function () {
            var activeElements = document.getElementsByClassName("layui-bg-blue active");
            name = activeElements[0].querySelector('td[data-field="name"]').textContent.trim().split('\n')[0];
            start_container(name)
                .then(() => {
                    delayedReload();
                })
                .catch((error) => {
                    console.error("An error occurred:", error);
                });
        }

        var stop = document.getElementById('stop');
        stop.onclick = function () {
            var activeElements = document.getElementsByClassName("layui-bg-blue active");
            name = activeElements[0].querySelector('td[data-field="name"]').textContent.trim().split('\n')[0];
            stop_container(name)
                .then(() => {
                    delayedReload();
                })
                .catch((error) => {
                    console.error("An error occurred:", error);
                });
        }

        var update = document.getElementById('update');
        update.onclick = function () {
            update.disable = true;
            update_container()
                .then(() => {
                    delayedReload();
                })
                .catch((error) => {
                    update.disable = false;
                    console.error("An error occurred:", error);
                });
        }

        var rename = document.getElementById('rename');
        rename.onclick = function () {
            rename.disable = true;
            var activeElements = document.getElementsByClassName("layui-bg-blue active");
            name = activeElements[0].querySelector('td[data-field="name"]').textContent.trim().split('\n')[0];
            layer.prompt({title: '请输入新的名称', formType: 0}, function (new_name, index) {
                layer.close(index);
                rename_container(name, new_name)
                    .then(() => {
                        delayedReload();
                    })
                    .catch((error) => {
                        new_name.disable = false;
                        console.error("An error occurred:", error);
                    });
            });
        }

        var change_tag = document.getElementById('change_tag');
        change_tag.onclick = function () {
            change_tag.disable = true;
            layer.prompt({title: '请输入 镜像名:tag', formType: 0}, function (image_name_and_tag, index) {
                layer.close(index);
                update_container(image_name_and_tag, true)
                    .then(() => {
                        delayedReload();
                    })
                    .catch((error) => {
                        change_tag.disable = false;
                        console.error("An error occurred:", error);
                    });
            });
        }

        async function update_container(image_name_and_tag = "", change_image_name_and_tag = false) {
            try {
                var activeElements = document.getElementsByClassName("layui-bg-blue active");
                name = activeElements[0].querySelector('td[data-field="name"]').textContent.trim().split('\n')[0];
                state = activeElements[0].querySelector("span").className;
                new_name = name + '_old';
                if (state !== "layui-badge-dot")
                    await stop_container(name);
                if (!change_image_name_and_tag) {
                    image_name_and_tag = activeElements[0].querySelector('td[data-field="image_and_tag"]').textContent;
                }
                console.log(image_name_and_tag)

                let promise = new Promise((resolve) => {
                    let matches = image_name_and_tag.match(/\//g);
                    let count = matches ? matches.length : 0;
                    if (2 <= count) {
                        resolve();
                        return;
                    }
                    layer.confirm('使用的镜像为' + image_name_and_tag, {
                        title: '是否使用代理',
                        btn: ['使用代理', '不使用代理']
                    }, function (index) {
                        image_name_and_tag = "dockerproxy.com/" + image_name_and_tag
                        layer.close(index);
                        resolve();
                    }, function (index) {
                        layer.close(index);
                        resolve();
                    });
                });
                await promise;
                console.log(image_name_and_tag)
                await get_new_image(image_name_and_tag);
                await rename_container(name, new_name);
                await create_container(name, image_name_and_tag);
                await start_container(name);
                var del_name = name + '_old';
                console.log(del_name);
                await delete_confirm(del_name);
            } catch (error) {
                console.error("An error occurred:", error);
            }
        }

        function start_container(name) {
            return new Promise((resolve, reject) => {
                var csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
                var xhr = new XMLHttpRequest();
                var url = "start_container/";
                var method = "POST";
                xhr.open(method, url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                var data = {name: name};
                var params = JSON.stringify(data);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            console.log(response);
                            if (response['status'] === 'start_success') {
                                layer.msg('启动容器成功', {time: 0});
                                resolve();
                            } else if (response['status'] === 'start_failed') {
                                layer.alert('启动容器失败', {icon: 5});
                                reject();
                            } else {
                                layer.alert('启动容器失败', {icon: 5});
                                reject();
                            }
                        } catch (error) {
                            console.error("Failed to parse JSON response:", error);
                            layer.alert('启动容器出现错误，请联系开发者', {icon: 5});
                        }
                    }
                };
                layer.msg('正在启动容器', {time: 0});
                setTimeout(function () {
                    xhr.send(params);
                }, 1500); // 暂缓3秒执行xhr.send(params)
            });
        }

        function stop_container(name) {
            return new Promise((resolve, reject) => {
                var csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
                var xhr = new XMLHttpRequest();
                var url = "stop_container/";
                var method = "POST";
                xhr.open(method, url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                var data = {name: name};
                var params = JSON.stringify(data);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            console.log(response);
                            if (response['status'] === 'stop_success') {
                                layer.msg('停止容器成功', {time: 0});
                                resolve();
                            } else if (response['status'] === 'stop_failed') {
                                layer.alert('停止容器失败', {icon: 5});
                                reject();
                            } else {
                                layer.alert('停止容器失败', {icon: 5});
                                reject();
                            }
                        } catch (error) {
                            console.error("Failed to parse JSON response:", error);
                            layer.alert('停止容器出现错误，请联系开发者', {icon: 5});
                        }
                    }
                };
                layer.msg('正在停止容器', {time: 0});
                setTimeout(function () {
                    xhr.send(params);
                }, 1500); // 暂缓3秒执行xhr.send(params)
            });

        }

        async function rename_container(name, new_name) {
            return new Promise((resolve, reject) => {
                var csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
                var xhr = new XMLHttpRequest();
                var url = "rename_container/";
                var method = "POST";
                xhr.open(method, url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                var data = {name: name, new_name: new_name};
                var params = JSON.stringify(data);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            console.log(response);
                            if (response['status'] === 'rename_success') {
                                console.log('重命名成功');
                                layer.msg('重命名旧容器成功', {time: 0});
                                resolve();
                            } else if (response['status'] === 'rename_failed') {
                                layer.alert('重命名旧容器失败', {icon: 5});
                                reject();
                            } else {
                                layer.alert('重命名旧容器失败', {icon: 5});
                                reject();
                            }
                        } catch (error) {
                            console.error("Failed to parse JSON response:", error);
                            layer.alert('重命名旧容器出现错误，请联系开发者', {icon: 5});
                        }
                    }
                };
                layer.msg('正在重命名旧容器', {time: 0});
                setTimeout(function () {
                    xhr.send(params);
                }, 1500); // 暂缓3秒执行xhr.send(params)
            });
        }

        function get_new_image(image_name_and_tag) {
            return new Promise((resolve, reject) => {
                var csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
                var xhr = new XMLHttpRequest();
                var url = "/imagesManager/get_new_image/";
                var method = "POST";
                xhr.open(method, url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                var data = {image_name_and_tag: image_name_and_tag};
                var params = JSON.stringify(data);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            console.log(response);
                            if (response['status'] === 'get_new_image_success') {
                                layer.msg('拉取新镜像成功', {time: 0});
                                resolve();
                            } else if (response['status'] === 'get_new_image_failed') {
                                layer.alert('拉取新镜像失败', {icon: 5});
                                reject();
                            } else {
                                layer.alert('拉取新镜像失败', {icon: 5});
                                reject();
                            }
                        } catch (error) {
                            console.error("Failed to parse JSON response:", error);
                            layer.alert('拉取新镜像出现错误，请检查网络，可以尝试更换docker仓库', {icon: 5});
                        }
                    }
                };
                layer.msg('正在拉取新镜像', {time: 0});
                setTimeout(function () {
                    xhr.send(params);
                }, 1500); // 暂缓3秒执行xhr.send(params)
            });

        }

        function create_container(name, image_name_and_tag) {
            return new Promise((resolve, reject) => {
                var csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
                var xhr = new XMLHttpRequest();
                var url = "create_container/";
                var method = "POST";
                xhr.open(method, url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                var data = {name: name, image_name_and_tag: image_name_and_tag};
                var params = JSON.stringify(data);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            console.log(response);
                            if (response['status'] === 'create_success') {
                                layer.msg('创建新容器成功', {time: 0});
                                resolve();
                            } else if (response['status'] === 'create_failed') {
                                layer.alert('创建新容器失败', {icon: 5});
                                reject();
                            } else {
                                layer.alert('创建新容器失败', {icon: 5});
                                reject();
                            }
                        } catch (error) {
                            console.error("Failed to parse JSON response:", error);
                            layer.alert('创建新容器出现错误，请联系开发者', {icon: 5});
                        }
                    }
                };
                layer.msg('正在创建新容器', {time: 0});
                setTimeout(function () {
                    xhr.send(params);
                }, 1500); // 暂缓3秒执行xhr.send(params)
            });

        }

        function delete_container(name) {
            return new Promise((resolve, reject) => {
                var csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
                var xhr = new XMLHttpRequest();
                var url = "delete_container/";
                var method = "POST";
                xhr.open(method, url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
                var data = {name: name};
                var params = JSON.stringify(data);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            console.log(response);
                            if (response['status'] === 'delete_success') {
                                layer.msg('删除旧容器成功', {time: 0});
                                resolve();
                            } else if (response['status'] === 'delete_failed') {
                                layer.alert('删除旧容器失败', {icon: 5});
                                reject();
                            } else {
                                layer.alert('删除旧容器失败', {icon: 5});
                                reject();
                            }
                        } catch (error) {
                            console.error("delete_container Failed");
                            layer.alert('删除旧容器出现错误，请联系开发者', {icon: 5});
                        }
                    }
                };
                layer.msg('正在删除旧容器', {time: 0});
                setTimeout(function () {
                    xhr.send(params);
                }, 1500); // 暂缓3秒执行xhr.send(params)
            });
        }

        function delete_confirm(del_name) {
            return new Promise((resolve, reject) => {
                layer.confirm('是否删除旧容器？', {
                    btn: ['是', '否'], //按钮
                    skin: 'layui-layer-molv'
                }, async function () {
                    await delete_container(del_name);
                    resolve();
                }, function () {
                    layer.msg('更新完成', {
                        time: 2000, //20s后自动关闭
                    });
                    reject();
                });
            });
        }

        function delayedReload() {
            setTimeout(function () {
                location.reload();
            }, 2500); // 延迟3秒钟（或3000毫秒）
        }
    </script>

    <script>
        const table = document.getElementById('container_table');
        const rowCount = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;
        document.getElementById('rowCountDisplay').innerText = rowCount;
    </script>
{% endblock %}


